import os
import sys

import pandas as pd
import hanlp
import re

from api.db.db_models import Synonyms, DB

from api.db.services.common_service import CommonService


class SynonymService(CommonService):
    model = Synonyms

    @classmethod
    @DB.connection_context()
    def get_list(cls, page_number, items_per_page, orderby, desc, id, normalized_word, standard_word):
        sessions = cls.model.select()
        if id:
            sessions = sessions.where(cls.model.id == id)
        if normalized_word:
            sessions = sessions.where(cls.model.normalized_word == normalized_word)
        if standard_word:
            sessions = sessions.where(cls.model.standard_word == standard_word)
        if desc:
            sessions = sessions.order_by(cls.model.getter_by(orderby).desc())
        else:
            sessions = sessions.order_by(cls.model.getter_by(orderby).asc())

        sessions = sessions.paginate(page_number, items_per_page)

        return list(sessions.dicts())


# 同义词替换逻辑
def replace_synonym_query(query):
    synonyms_map = get_synonyms_map()
    # 转大写再使用HanLP分词
    upper_query = query.upper()
    tok = hanlp.load(hanlp.pretrained.tok.COARSE_ELECTRA_SMALL_ZH)
    tok.dict_combine = set(synonyms_map.keys())
    seg_list = tok(upper_query)
    # 输入问题中涉及的同义词map
    synonyms_standard_map = dict()
    for item in seg_list:
        standard_word = synonyms_map.get(item.replace(" ", "").upper())
        if standard_word:
            synonyms_standard_map[item] = standard_word
    synonym_replaced_query = replace_synonym(query, synonyms_standard_map)
    return synonym_replaced_query


# 根据同义词：标准词字典进行同义词替换
def replace_synonym(query, synonyms_standard_map):
    if not synonyms_standard_map:
        return query
    synonym_new_query = query
    for item in synonyms_standard_map.items():
        normalized_word = item[0]
        standard_word = item[1]
        standard_words = standard_word.split(" ")
        result = ["(" + word + ")" for word in standard_words]
        re_exp1 = "?(\\s*)?".join(result)
        re_exp = "(?i)(((\\s*)?)+(" + re_exp1 + ")+)|(" + normalized_word + ")"
        synonym_new_query = re.sub(re_exp, "" + standard_word, synonym_new_query)
    return synonym_new_query.strip()


# 获取同义词映射字典
def get_synonyms_map():
    synonyms_map = dict()
    synonyms_list = [m.to_dict() for m in SynonymService.get_all()]
    for synonym in synonyms_list:
        synonyms_map[synonym['normalized_word'].replace(" ", "")] = synonym['standard_word']
    return synonyms_map


# 插入同义词
def write_synonyms_bulk(file_path):
    df = pd.read_excel(file_path)
    for item in df.to_dict(orient='records'):
        if SynonymService.get_by_id(item['id'])[1] is None:
            SynonymService.insert(**item)
        else:
            SynonymService.update_by_id(item['id'], item)


if __name__ == '__main__':
    # synonyms_path = "../同义词测试.xlsx"
    # write_synonyms_bulk(synonyms_path)
    print(replace_synonym_query("如何查看企业客户拜访记录？"))
    pass